package com.hnyfkj.jyindustry.biz.systemplate.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hnyfkj.jyindustry.biz.area.service.AreaService;
import com.hnyfkj.jyindustry.biz.parameter.service.ParameterService;
import com.hnyfkj.jyindustry.biz.systemplate.dao.SysTemplateDao;
import com.hnyfkj.jyindustry.biz.systemplate.dto.SysTemplateInsertDto;
import com.hnyfkj.jyindustry.biz.systemplate.dto.SysTemplateQueryDto;
import com.hnyfkj.jyindustry.biz.systemplate.dto.SysTemplateUpdateDto;
import com.hnyfkj.jyindustry.biz.systemplate.entity.SysTemplateEntity;
import com.hnyfkj.jyindustry.biz.systemplate.service.SysTemplateService;
import com.hnyfkj.jyindustry.common.utils.MulFileToFileUtil;
import com.hnyfkj.jyindustry.common.utils.PageUtils;

/**
 * @author zjq
 *
 * @Description
 *
 * @date 2020年12月10日
 */
@Service("sysTemplateService")
public class SysTemplateServiceImpl extends ServiceImpl<SysTemplateDao, SysTemplateEntity>
		implements SysTemplateService {

	@Autowired
	private SysTemplateDao sysTemplateDao;
	@Autowired
	private ParameterService parameterService;
	@Autowired
	private AreaService areaService;

	@Override
	public int insert(final SysTemplateInsertDto sysTemplateDto) {
		final SysTemplateEntity sysTemplate = new SysTemplateEntity();
		BeanUtils.copyProperties(sysTemplateDto, sysTemplate);
		sysTemplate.setLike1(cheKCheked(sysTemplateDto.getLike1()));
		sysTemplate.setLike2(cheKCheked(sysTemplateDto.getLike2()));
		sysTemplate.setLike3(cheKCheked(sysTemplateDto.getLike3()));
		sysTemplate.setLike4(cheKCheked(sysTemplateDto.getLike4()));
		sysTemplate.setLike5(cheKCheked(sysTemplateDto.getLike5()));
		sysTemplate.setLike6(cheKCheked(sysTemplateDto.getLike6()));
		sysTemplate.setOpen(cheKCheked(sysTemplateDto.getOpen()));
		sysTemplate.setClose(cheKCheked(sysTemplateDto.getClose()));
		if (sysTemplateDto.getInfo() != null) {
			sysTemplate.setInfo(StringEscapeUtils.escapeHtml4(sysTemplateDto.getInfo()));
		}
		sysTemplate.setSelectTable(sysTemplate.getSelectTable());
		sysTemplate.setTableSelect(sysTemplate.getTableSelect());
		return sysTemplateDao.insert(sysTemplate);
	}

	@Override
	public int update(SysTemplateUpdateDto sysTemplateDto) {
		final SysTemplateEntity sysTemplate = new SysTemplateEntity();
		BeanUtils.copyProperties(sysTemplateDto, sysTemplate);
		if (sysTemplateDto.getInfo() != null) {
			sysTemplate.setInfo(StringEscapeUtils.escapeHtml4(sysTemplateDto.getInfo()));
		}
		sysTemplate.setSelectTable(sysTemplate.getSelectTable());
		sysTemplate.setTableSelect(sysTemplate.getTableSelect());
		return sysTemplateDao.updateById(sysTemplate);
	}

	@Override
	public PageUtils<SysTemplateEntity> selectListDto(SysTemplateQueryDto queryDto) {
		if (queryDto != null && queryDto.getEnterTime() != null) {
			if (queryDto.getEnterTime().isEmpty()) {
				queryDto.setStartTime("");
				queryDto.setEndTime("");
			} else {
				queryDto.setStartTime(queryDto.getEnterTime().split(" - ")[0]);
				queryDto.setEndTime(queryDto.getEnterTime().split(" - ")[1]);
			}
		}
		PageHelper.startPage(queryDto.getPage(), queryDto.getLimit());
		PageInfo<SysTemplateEntity> pageInfo = new PageInfo<>(sysTemplateDao.selectListDto(queryDto));
		pageInfo.setPageNum(queryDto.getPage());
		return PageUtils.pageOf(pageInfo);
	}

	@Override
	public int delectBatch(String[] memberIds) {
		return sysTemplateDao.deleteBatchIds(Arrays.asList(memberIds));
	}

	public Boolean cheKCheked(String result) {
		if (result != null && "on".equals(result)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public JSONObject uploadImage(MultipartFile[] image) throws Exception {
		JSONObject resultJson = new JSONObject();
		JSONObject data = new JSONObject();
		List<String> list = new ArrayList<String>();
		String msg = "上传成功";
		Integer code = 1;
		if (image.length > 0) {
			for (MultipartFile img : image) {
				// 请求接口传图片
				RestTemplate rest = new RestTemplate();
				FileSystemResource resource = new FileSystemResource(MulFileToFileUtil.multipartFileToFile(img));
				MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
				param.add("file", resource); // MultipartFile的名称
				String uploadPath = parameterService.getSysParameter("fileUpload") + ("/");
				String rs = rest.postForObject(uploadPath + "hnyfkj-file-server/common/upload", param, String.class);
				String resultUrl = "";
				if (rs != null && !"".equals(rs)) {
					JSONObject json = JSONObject.parseObject(rs);
					if (json.getInteger("code") == 200) {
						resultUrl = json.getString("result");
						list.add(uploadPath + resultUrl);
					} else {
						data.put("url", list);
						resultJson.put("msg", "上传失败");
						resultJson.put("code", 0);
						resultJson.put("data", data);
						return resultJson;
					}
				} else {
					data.put("url", list);
					resultJson.put("msg", "上传失败");
					resultJson.put("code", 0);
					resultJson.put("data", data);
					return resultJson;
				}
				// 上传成功后删除缓存图片
				if (resource.getFile().exists()) {
					resource.getFile().delete();
				}
			}
		} else {
			msg = "请选择图片";
			code = 0;
		}
		data.put("url", list);
		resultJson.put("msg", msg);
		resultJson.put("code", code);
		resultJson.put("data", data);
		return resultJson;
	}

	@Override
	public String imageUpload(MultipartFile image) throws Exception {
		JSONObject resultJson = new JSONObject();
		String msg = "上传失败";
		Integer code = 0;
		if (image != null) {
			// 请求接口传图片
			RestTemplate rest = new RestTemplate();
			FileSystemResource resource = new FileSystemResource(MulFileToFileUtil.multipartFileToFile(image));
			MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
			param.add("file", resource); // MultipartFile的名称
			String uploadPath = parameterService.getSysParameter("fileUpload") + ("/");
			try {
				String rs = rest.postForObject(uploadPath + "hnyfkj-file-server/common/upload", param, String.class);
				String resultUrl = "";
				if (rs != null && !"".equals(rs)) {
					JSONObject json = JSONObject.parseObject(rs);
					if (json.getInteger("code") == 200) {
						resultUrl = json.getString("result");
						msg = uploadPath + resultUrl;
						code = 1;
					}
				}else {
					resultJson.put("msg", msg);
					resultJson.put("code", code);
					return resultJson.toJSONString();
				}
				// 上传成功后删除缓存图片
				if (resource.getFile().exists()) {
					resource.getFile().delete();
				}
			} catch (Exception e) {
				resultJson.put("msg", msg);
				resultJson.put("code", code);
				return resultJson.toJSONString();
			}
			
		} else {
			msg = "请选择图片";
		}
		resultJson.put("msg", msg);
		resultJson.put("code", code);
		return resultJson.toJSONString();
	}

	@Override
	public SysTemplateEntity getTemplateById(Integer id) {
		final SysTemplateEntity sysTemplateEntity = this.getById(id);
		if (sysTemplateEntity.getArea() != null && sysTemplateEntity.getArea() != "") {
			String[] areaArray = sysTemplateEntity.getArea().split(",");
			sysTemplateEntity.setArea(areaService.getOneById(areaArray[0]).getAreaName()
					+ areaService.getOneById(areaArray[1]).getAreaName()
					+ areaService.getOneById(areaArray[2]).getAreaName()
					+ areaService.getOneById(areaArray[3]).getAreaName());
		}
		return sysTemplateEntity;
	}
}
